#coding:utf-8
import socket
import sys
import struct
import random
import time
import binascii

#校验函数,计算校验值
def checksumm(msg):
	s = 0
	#
	for i in range(0, len(msg), 2):
		w = (ord(msg[i]) << 8) + (ord(msg[i+1]))
		s = s + w
		
	s = (s >> 16) + (s & 0xffff);
	#s = s + (s >> 16); 
	#补充和掩盖4字节的short
	s = ~s & 0xffff
	
	return s

source_port = random.randint(1024, 65000)
#print source_port
sport = struct.pack("!H", source_port)
#print binascii.hexlify(sport)

dest_port = 80
dport = struct.pack("!H", dest_port)
#print binascii.hexlify(dport)

seq_time = time.time()
#print seq_time
seq = socket.htonl(int(seq_time))
#print seq
seq1 = struct.pack("!L",seq)
#print binascii.hexlify(seq1)

ack_seq = 0
aseq = struct.pack("!L",ack_seq)
#print binascii.hexlify(aseq)

doff = 5
offset_res = (doff << 4) + 0  #80
offset = struct.pack("!B", offset_res)
#print binascii.hexlify(offset)

fin = 0
syn = 1
rst = 0
psh = 0
ack = 0
urg = 0
tcp_flags = fin + (syn << 1) + (rst << 2) + (psh << 3) + (ack << 4) + (urg << 5)
#print tcp_flags
flags = struct.pack("!B",tcp_flags)
#print binascii.hexlify(flags)

windows = socket.htons(5840)
win = struct.pack("!H", windows)
#print binascii.hexlify(win)

checksum = 0
check = struct.pack("!H",checksum)
#print binascii.hexlify(check)

urg_ptr = 0
urg = struct.pack("!H", urg_ptr)
#print binascii.hexlify(urg)

tcp_header = struct.pack("!HHLLBBHHH", source_port, dest_port, seq, ack_seq, offset_res, tcp_flags, windows, checksum, urg_ptr)
#print binascii.hexlify(tcp_header)

#伪报头字段
source_ip = "192.168.1.102"
dest_ip = "192.168.1.100"
source_address = socket.inet_aton( source_ip )
dest_address = socket.inet_aton( dest_ip )
placeholder = 0
protocol = socket.IPPROTO_TCP
tcp_length = len(tcp_header)

psh = struct.pack("!4s4sBBH", source_address, dest_address, placeholder, protocol, tcp_length)
#print binascii.hexlify(psh)
psh = psh + tcp_header
#print binascii.hexlify(psh)

tcp_check = checksumm(psh)
#print tcp_check

#重新构造TCP报头，填写正确的校验值
tcp_header = struct.pack("!HHLLBBH", source_port, dest_port, seq, ack_seq, offset_res, tcp_flags, windows) + struct.pack("H", tcp_check) + struct.pack("!H", urg_ptr)
print binascii.hexlify(tcp_header)

#创建一个raw socket
try:
	s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)  #IPPROTO_TCP,socket.IPPROTO_RAW)
except socket.error , msg:
	print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()

#
packet = ''
packet = tcp_header

s.sendto(packet, (dest_ip, 0))
